package com.xjscrm.server.common.util;

import java.time.*;
import java.util.Date;
import java.util.Random;

/**
 * @author liuqi
 * @date 2024年04月19日 17:59
 */
public class TimeTools {
    /**
     * 获取2个时间格式之间的随机值
     *
     * @param startTime
     * @param endTime
     * @return java.time.LocalTime
     * @author jitwxs
     * @date 2024/4/19 17:59
     */
    public static LocalTime getRandomTimeBetween(LocalTime startTime, LocalTime endTime) {
        if (startTime.isAfter(endTime)) {
            return null;
        }
        int startSecondOfDay = startTime.toSecondOfDay();
        int endSecondOfDay = endTime.toSecondOfDay();
        int randomSecondOfDay = new Random().nextInt(endSecondOfDay - startSecondOfDay) + startSecondOfDay;

        return LocalTime.ofSecondOfDay(randomSecondOfDay);
    }

    /**
     * 从LocalDate和LocalTime 组装成Date
     *
     * @param localDate
     * @param localTime
     * @return java.time.LocalTime
     * @author jitwxs
     * @date 2024/4/19 17:59
     */
    public static Date getDateByLocalDayAndLocalTime(LocalDate localDate, LocalTime localTime) {
        // 将LocalDate和LocalTime合并为LocalDateTime
        LocalDateTime localDateTime = localDate.atTime(localTime);
        // 将LocalDateTime转换为Date
        Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
        return date;
    }

    /**
     * 从Date格式转换成LocalDate
     *
     * @param date
     * @return java.time.LocalTime
     * @author jitwxs
     * @date 2024/4/19 17:59
     */
    public static LocalDate getLocalDateFromDate(Date date) {
        if (date == null) {
            return null;
        }
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDate localDate = instant.atZone(zoneId).toLocalDate();
        return localDate;
    }

    /**
     * 从Date格式转换成LocalDateTime
     *
     * @param date
     * @return java.time.LocalTime
     * @author jitwxs
     * @date 2024/4/19 17:59
     */
    public static LocalDateTime getLocalDateTimeFromDate(Date date) {
        if (date == null) {
            return null;
        }
        Instant instant = date.toInstant();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        return localDateTime;
    }

    public static void main(String[] args) {

        System.out.println(getLocalDateTimeFromDate(new Date()));
    }


}
